package org.example.rtc.controller;

import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import org.example.rtc.model.entity.User;
import org.example.rtc.model.entity.dto.R;
import org.example.rtc.service.UserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequiredArgsConstructor
public class LoginController {

    private final UserService userService;

    @PostMapping("/login")
    public R<Map<String,String>> login(@RequestBody Map<String,String> params) {
        User user = userService.getUserByUsername(params.get("username"));
        if (user == null) {
            return R.error("用户不存在");
        }
        // 模拟用户验证
        if ( params.get("password").equals(user.getPwd())) {
            // 登录成功，生成 Token
            StpUtil.login(user.getId()); // 1001 是用户 ID
            String tokenValue = StpUtil.getTokenValue();
            Map<String, String> stringStringHashMap = new HashMap<>();
            stringStringHashMap.put("token", tokenValue);
            stringStringHashMap.put("username", user.getName());
            stringStringHashMap.put("localhospital", user.getLocalhospital());
            stringStringHashMap.put("department", user.getDepartment());
            stringStringHashMap.put("department", user.getDepartment());
            stringStringHashMap.put("id", user.getId().toString());
            return R.success(stringStringHashMap);
        }
        return R.error("Login failed!");
    }

    @PostMapping("/logout")
    public String logout() {
        // 注销当前用户
        StpUtil.logout();
        return "Logout successful!";
    }
}